import store from "../store";
const fs = require("fs");
const path = require("path");
import ls from "./crypto";

export function ReadFile() {
  const base = store.state.app.static;
  const filepath = path.join(base, "storage");
  const jsonData = fs.readFileSync(filepath, "utf-8");

  if (jsonData) {
    const d = ls.getItem(jsonData);
    if (d) {
      return JSON.parse(d);
    } else {
      return {};
    }
  } else {
    return {};
  }
}

export async function writeFile(data, type) {
  try {
    let obj;
    if (!type || type === "assign") {
      const o = ReadFile();
      obj = Object.assign(o, data);
    } else if (type === "clear") {
      obj = data;
    }

    const jsonData = JSON.stringify(obj);
    const d = ls.setItem(jsonData);

    const base = store.state.app.static;
    const filepath = path.join(base, "storage");

    const res = fs.writeFileSync(filepath, d);
  } catch (e) {
    console.log("数据存储失败");
  }
}
